package scala.day01

import java.io.{BufferedReader, BufferedWriter, FileReader, FileWriter}

import scala.io.{BufferedSource, Source}

object Demo07IO {
  def main(args: Array[String]): Unit = {
    /**
      * 文件读写
      */
    //使用java的方式
    //scala中的异常默认抛出
    val fileReader = new FileReader("data/students.txt")
    //缓冲流
    val bufferedReader = new BufferedReader(fileReader)
    //读取第一行
    var line: String = bufferedReader.readLine()//注意这里要使用var
    while (line != null){
      println(line)
      //读取下一行
      line = bufferedReader.readLine()
    }
    bufferedReader.close()
    println("=" * 100)
    //println("=".*(100))
    /**
      * 使用scala读取数据
      */
    val source: BufferedSource = Source.fromFile("data/students.txt")

    /**
      * 迭代器
      * 迭代器只能迭代一次
      */
    val lines: Iterator[String] = source.getLines()
    for (elem <- lines) {
      println(elem)
    }
  }
  //链式调用
  private val array: Array[String] = Source.fromFile("data/students.txt").getLines().toArray
  /**
    * 保存数据使用的是Java的方法
    * 输出流
    */
  private val bufferedWriter = new BufferedWriter(new FileWriter("data/out"))
  for (elem <- array) {
    bufferedWriter.write(elem)
    bufferedWriter.newLine()
    bufferedWriter.flush()
  }
  bufferedWriter.close()
}
